<template>
  <div class="flex gap-2">
    <el-tag
      v-for="tag in isCollapsed ? visibleTags : dynamicTags"
      :key="tag"
      closable
      :disable-transitions="false"
      @close="handleClose(tag)"
    >
      {{ tag }}
    </el-tag>
    <span v-if="remainingTags > 0" class="ellipsis-tag" @click="toggleCollapse">
      {{ isCollapsed ? `+${remainingTags} more` : "Collapse" }}
    </span>
    <el-input
      v-if="inputVisible"
      ref="InputRef"
      v-model="inputValue"
      class="w-20"
      size="small"
      @keyup.enter="handleInputConfirm"
      @blur="handleInputConfirm"
    />
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, computed } from "vue";
import { ElInput } from "element-plus";

const props = defineProps({
  tagList: { type: Array<string>, default: () => ["ALL"] },
});

const maxVisibleTags = 5;
const inputValue = ref("");
const dynamicTags = ref(props.tagList);
const inputVisible = ref(false);
const InputRef = ref<InstanceType<typeof ElInput>>();
const isCollapsed = ref(true);

const visibleTags = computed(() => dynamicTags.value.slice(0, maxVisibleTags));
const remainingTags = computed(() => dynamicTags.value.length - maxVisibleTags);

const handleClose = (tag: string) => {
  dynamicTags.value.splice(dynamicTags.value.indexOf(tag), 1);
};

const handleInputConfirm = () => {
  if (inputValue.value) {
    dynamicTags.value.push(inputValue.value);
  }
  inputVisible.value = false;
  inputValue.value = "";
};

const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value;
};
</script>

<style scoped>
.ellipsis-tag {
  padding: 5px;
  color: #909399;
  cursor: pointer;
}
</style>
